package org.hilo.boot.core.mapper;

import java.util.Set;

import org.apache.ibatis.mapping.MappedStatement;

import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.MapperTemplate;
import tk.mybatis.mapper.mapperhelper.SqlHelper;

public class UpdateByRecordProvider extends MapperTemplate {
    
    public UpdateByRecordProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
        super(mapperClass, mapperHelper);
    }

    /**
     * 通过匹配record条件更新不为null的字段
     *
     * @param ms
     * @return
     */
    public String updateByRecord(MappedStatement ms) {
        Class<?> entityClass = getEntityClass(ms);
        StringBuilder sql = new StringBuilder();
        sql.append(SqlHelper.updateTable(entityClass, tableName(entityClass)));
        sql.append(SqlHelper.updateSetColumns(entityClass, "record", true, isNotEmpty()));
        sql.append(whereAllIfColumns(entityClass, "param"));
        return sql.toString();
    }
    
    
    /**
     * where所有列的条件，会判断是否!=null
     */
    public static String whereAllIfColumns(Class<?> entityClass, String entityName) {
        StringBuilder sql = new StringBuilder();
        sql.append("<where>");
        //获取全部列
        Set<EntityColumn> columnList = EntityHelper.getColumns(entityClass);
        //当某个列有主键策略时，不需要考虑他的属性是否为空，因为如果为空，一定会根据主键策略给他生成一个值
        for (EntityColumn column : columnList) {
            sql.append(SqlHelper.getIfNotNull(entityName, column, " AND " + column.getColumnEqualsHolder(entityName), false));
        }
        sql.append("</where>");
        return sql.toString();
    }

}
